package demo;

import com.sun.deploy.util.StringUtils;

import java.util.TreeMap;

/**
 * Trie树，只识别小写字母
 */
public class Trie {

    private class Node{

        public boolean isWord;
        public TreeMap<Character , Node> next;

        public Node(){
            this.isWord = false;
            next = new TreeMap<>();
        }

    }

    private Node root;
    private int size;

    public Trie(){
        root = new Node();
    }

    public void add(String word){

        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if( cur.next.get(c) == null ){
                //存储c的这个节点为null，那么就新增节点
                cur.next.put(c , new Node());
            }
            cur = cur.next.get(c);
        }

        // 判断单词是否之前就已经存在了，如果不存在，size才需要增加
        if(cur.isWord == false){
            cur.isWord = true;
            size++;
        }
    }


    public boolean contains(String word){
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if( cur.next.get(c) == null ){
                return false;
            }
            cur = cur.next.get(c);
        }

        return cur.isWord;
    }


    // Trie 前缀查找，查找前缀是否存在
    public boolean isPrefix( String prefix){
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if( cur.next.get(c) == null ){
                return false;
            }
            cur = cur.next.get(c);
        }

        return true;
    }



}
